package com.spl.msplayer;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.cookie.SetCookie;

import com.spl.msplayer.settings.SettingActivity;

import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.URLUtil;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class MainScreen extends Activity {

	public static String VIDEO_PATH_KEY = "VIDEO_PATH";
	public static String VIDEO_ORIENTATION_KEY = "VIDEO_ORIENTATION";
	public static String RESUME_FROM_NOTIFICATION = "FROMN";
	public static String ONLINE_STREAMING = "ONLINE_STREAMING";
	
	ListView listVideo;
	
	String[] ThumbProjection = {MediaStore.Video.Thumbnails._ID,
								MediaStore.Video.Thumbnails.WIDTH,
								MediaStore.Video.Thumbnails.HEIGHT};
	/*
     * Column index for the Thumbnails Video IDs.
     */
    private int thumbColumnIndex;
    /**
     * Cursor used to access the results from querying for images on the SD card.
     */
    private Cursor thumbCursor;
    
	String[] TitleProjection = {MediaStore.Video.VideoColumns._ID,
								MediaStore.Video.VideoColumns.TITLE,
								MediaStore.Video.VideoColumns.DURATION, 
								MediaStore.Video.VideoColumns.DESCRIPTION,
								MediaStore.Video.Media.DATA,
								};
    
    private Cursor dataCursor;
    private int titleColumnIndex;
    private int durationColumnIndex;
    private int thumbHeightColumnIndex;
    private int thumbWidthColumnIndex;
    private int desColumnIndex;
    private int dataColumnIndex;
    
    String[] videoID;
	
    ArrayList<VideoInfo> videos = new ArrayList<VideoInfo>();
    
    MediaPlayer player;
    
    static class ViewHolder {
        public TextView text;
        public ImageView image;
        public TextView durration;
      }
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_screen);
		
		player = new MediaPlayer();
		
		thumbCursor = getContentResolver().query(MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI, ThumbProjection, null, null, MediaStore.Video.Thumbnails._ID);
		dataCursor = getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, TitleProjection, null, null, MediaStore.Video.VideoColumns._ID);
		
		thumbColumnIndex = thumbCursor.getColumnIndex(MediaStore.Video.Thumbnails._ID);
		thumbWidthColumnIndex = thumbCursor.getColumnIndex(MediaStore.Video.Thumbnails.WIDTH);
		thumbHeightColumnIndex = thumbCursor.getColumnIndex(MediaStore.Video.Thumbnails.HEIGHT);
		
		titleColumnIndex = dataCursor.getColumnIndex(MediaStore.Video.VideoColumns.TITLE);
		durationColumnIndex = dataCursor.getColumnIndex(MediaStore.Video.VideoColumns.DURATION);
		dataColumnIndex = dataCursor.getColumnIndex(MediaStore.Video.Media.DATA);
		desColumnIndex = dataCursor.getColumnIndex(MediaStore.Video.VideoColumns.DESCRIPTION);
		
		int idIndex = dataCursor.getColumnIndex(MediaStore.Video.VideoColumns._ID);

		dataCursor.moveToFirst();
		thumbCursor.moveToFirst();
		String idString;
		String title;
		String duration;
		String width;
		String height;
		String thumbId;
		String des;
		String data;
		if(dataCursor.getCount() == thumbCursor.getCount()) {
			for(int i = 0; i < dataCursor.getCount(); i++) {

				thumbId = thumbCursor.getString(thumbColumnIndex);
				width = thumbCursor.getString(thumbWidthColumnIndex);
				height = thumbCursor.getString(thumbHeightColumnIndex);
				
				idString = dataCursor.getString(idIndex);
				title = dataCursor.getString(titleColumnIndex);
				duration = dataCursor.getString(durationColumnIndex);
				data = dataCursor.getString(dataColumnIndex);
				des = dataCursor.getString(desColumnIndex);
				Log.i("SUMPRO", "width:" + width);
				Log.i("SUMPRO", "height:" + height);
				Log.i("SUMPRO", "des:" + des);
				Log.i("SUMPRO", "data:" + data);
				
				VideoInfo item = new VideoInfo(thumbId, idString, title, Long.parseLong(duration), Integer.parseInt(width), Integer.parseInt(height), data);
				
				Log.i("SUMPRO", item.toString());
				
				videos.add(item);
				
				dataCursor.moveToNext();
				thumbCursor.moveToNext();
			}
		} else {
			Log.i("SUMPRO", "Data error");
		}
		listVideo = (ListView) findViewById(R.id.listView1);
		listVideo.setAdapter(new MyListAdapter(this));
		listVideo.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				
				
				
				Intent intent = new Intent(MainScreen.this, VideoPlayer.class);
				
				if(videos.size() > arg2) {
					intent.putExtra(VIDEO_PATH_KEY, videos.get(arg2).getDataPath());
					intent.putExtra(VIDEO_ORIENTATION_KEY, videos.get(arg2).getOrientation());
				}
				startActivity(intent);

			}
		});
		
		//Start player service
		Intent serviceIntent = new Intent(MainScreen.this, PlayerService.class);
		startService(serviceIntent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main_screen, menu);
		return true;
	}

	
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onContextItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		
		return super.onContextItemSelected(item);
	}



	/* (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		if(item.getTitle().equals("Settings")) {
			Intent intent = new Intent(MainScreen.this, SettingActivity.class);
			startActivity(intent);
		}
		if(item.getTitle().equals("Network Stream")) {
			getURLFromUser();
		}
			
		return super.onOptionsItemSelected(item);
	}



	private class MyListAdapter extends BaseAdapter {

		private Activity m_context;
		
		public MyListAdapter(Activity context) {
			this.m_context = context;
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return thumbCursor.getCount();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
			View rowView = arg1;
			if(rowView == null) {
				LayoutInflater inflater = m_context.getLayoutInflater();
				rowView = inflater.inflate(R.layout.listitem, null);
				ViewHolder viewHolder = new ViewHolder();
				viewHolder.text = (TextView) rowView.findViewById(R.id.lblTitle);
				viewHolder.image = (ImageView) rowView.findViewById(R.id.videoThumb);
				viewHolder.durration = (TextView) rowView.findViewById(R.id.lblDuration);
				rowView.setTag(viewHolder);
				
			}
			
			ViewHolder holder = (ViewHolder) rowView.getTag();

			
			if(videos != null && videos.size() > arg0) {
				VideoInfo item = videos.get(arg0);
				holder.image.setImageURI(Uri.withAppendedPath(MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI, "" + item.thumbId));
				holder.image.setScaleType(ImageView.ScaleType.FIT_XY);
				holder.text.setText("" + item.title);
				holder.durration.setText(makeDurationString(item.duration));
			}
			return rowView;
		}
		private String makeDurationString(long lDuration) {
			long time = lDuration / 1000;  
			String seconds = Integer.toString((int)(time % 60));  
			String minutes = Integer.toString((int)((time % 3600) / 60));  
			String hours = Integer.toString((int)(time / 3600));  
			for (int i = 0; i < 2; i++) {  
				if (seconds.length() < 2) {  
					seconds = "0" + seconds;  
				}  
				if (minutes.length() < 2) {  
					minutes = "0" + minutes;  
				}  
				if (hours.length() < 2) {  
					hours = "0" + hours;  
				}  
			} 
			
			return (hours + ":" + minutes + ":" + seconds);
		}
	}

	private void getURLFromUser() {
		LayoutInflater inflater = this.getLayoutInflater();
		View dialogInterface = inflater.inflate(R.layout.urldialog, null);
		final EditText url = (EditText)dialogInterface.findViewById(R.id.txtURL);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Video URL");
		
		builder.setPositiveButton("Ok", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				Log.i("SUMPRO", "URL " + url.getText().toString());
				if(URLUtil.isValidUrl(url.getText().toString())) {
					Intent intent = new Intent(MainScreen.this, VideoPlayer.class);
					intent.putExtra(ONLINE_STREAMING, true);
					intent.putExtra(VIDEO_PATH_KEY, url.getText().toString());
					intent.putExtra(VIDEO_ORIENTATION_KEY, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
					startActivity(intent);
				}
			}
		});
		builder.setNegativeButton("Cancel", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		});
		
		
		
		builder.setView(dialogInterface);
		Dialog getULRDialog = builder.create();
		getULRDialog.show();
	}
	
	@Override
	protected void onDestroy() {
		thumbCursor.close();
		dataCursor.close();
		super.onDestroy();
	}

	
	
	
}
